package com.hd.trans.files.aty

import android.animation.ObjectAnimator
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import com.hd.trans.R
import com.hd.trans.databinding.ActivityMediaAlbumBinding
import com.hd.trans.db.bean.MediaItem
import com.hd.trans.files.adapter.VideoAlbumAdapter
import com.hd.trans.files.bean.Album
import com.hd.trans.files.bean.MediaOptions
import com.hd.trans.files.model.MediaAlbumViewModel
import com.hd.trans.ui.base.BaseActivity
import com.hd.trans.utils.HDToastUtil
import com.hd.trans.widgets.AlbumDialog

class MediaAlbumActivity : BaseActivity() {

    companion object{
        const val TAG_MEDIA_OPTIONS: String = "TAG_MEDIA_OPTIONS"
        const val TAG_RESULT: String = "TAG_RESULT"
    }
    lateinit var binding: ActivityMediaAlbumBinding

    lateinit var viewModel: MediaAlbumViewModel

    lateinit var adapter: VideoAlbumAdapter

    lateinit var mAlbumPop: AlbumDialog

    lateinit var mMediaOptions: MediaOptions

    var mMaxSelectedNumber: Int = 1

    private var animator: ObjectAnimator? = null


    override fun getLayoutId(): Int {
        return R.layout.activity_media_album
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        initData()
        initView()
        attachListener()
    }

    private fun initData() {
        if (!fromIntent.hasExtra(TAG_MEDIA_OPTIONS)) {
            Log.e("MediaAlbumActivity","MediaOptions is empty")
            finish()
            return
        }
        mMediaOptions = fromIntent.getParcelableExtra(TAG_MEDIA_OPTIONS)!!

        mMaxSelectedNumber = mMediaOptions.max

        binding = DataBindingUtil.setContentView(this, R.layout.activity_media_album)

        viewModel = MediaAlbumViewModel(this, mMediaOptions)
        lifecycle.addObserver(viewModel)

        viewModel.observeMediaList().observe(this) { list ->
            adapter.submitListOnSort(list)
        }

        viewModel.observeSelectedMediaItemMap().observe(this) { set ->
            binding.videoSelectedCountTv.text = getString(
                R.string.trans_album_import,
                set.size,
                mMaxSelectedNumber
            )
            binding.videoSelectedCountTv.isEnabled = set.size > 0
        }

        viewModel.albumMutableLiveData.observe(this) { list ->
            mAlbumPop.setData(list)
        }

        mAlbumPop = AlbumDialog(this, viewModel.mediaOptions)
        mAlbumPop!!.setCallback {
            selectAlbum(it)
        }
        mAlbumPop!!.setShowCallback {
            updateArrow(it)
        }

        viewModel.load()
    }

    private fun initView() {
        binding.recyclerview.setItemViewCacheSize(6)
        binding.recyclerview.layoutManager = GridLayoutManager(this, 3)
        adapter = VideoAlbumAdapter()
        adapter.setSelectedMediaItemSet(viewModel.observeSelectedMediaItemMap())
        binding.recyclerview.adapter = adapter

    }

    private fun attachListener() {
        binding.backView.setOnClickListener { finish() }
        binding.titleText.setOnClickListener { mAlbumPop.showFromBottom() }
        binding.arrowDown.setOnClickListener { mAlbumPop.showFromBottom() }
        binding.videoSelectedCountTv.setOnClickListener {
            var list: ArrayList<MediaItem> = java.util.ArrayList()
            var map = viewModel.observeSelectedMediaItemMap().value
            for (entry: MutableMap.MutableEntry<Long, MediaItem> in map!!) {
                if (checkFileLimit(entry.value)) {
                    list.add(entry.value)
                }else{
                    return@setOnClickListener
                }
            }
            var intent = Intent()
            intent.putExtra(TAG_RESULT, list)
            setResult(RESULT_OK, intent)
            finish()
        }
        adapter.setOnItemChildClickListener { view, m, position ->
            var set = viewModel.observeSelectedMediaItemMap().value
            var selected = false
            if (set != null) {
                if (set.contains(m.id)) {
                    set.remove(m.id)
                } else {
                    while (set.size >= mMaxSelectedNumber) {
                        var removeEntry: MutableMap.MutableEntry<Long, MediaItem>? = null
                        for (entry: MutableMap.MutableEntry<Long, MediaItem> in set) {
                            removeEntry = entry
                            break
                        }
                        set.remove(removeEntry?.key)
                        adapter.updateMediaItem(removeEntry?.value)
                    }
                    set[m.id] = m
                    selected = true
                }
                viewModel.updateSelectedMediaItem(set)
                view.isSelected = selected
                adapter.notifyItemChanged(position)
            }
        }

    }

    private fun selectAlbum(album: Album) {
        viewModel.load(album)
        binding.titleText.text = album.getmDisplayName()
    }

    private fun updateArrow(popShow: Boolean) {
        if (animator != null && animator!!.isRunning) {
            animator!!.cancel()
        }
        animator = ObjectAnimator.ofFloat(
            binding.arrowDown,
            "rotation",
            if (popShow) 0f else 180f,
            if (popShow) 180f else 0f
        )
        animator!!.duration = 200
        animator!!.start()
    }

    private fun checkFileLimit(mediaItem: MediaItem): Boolean {
        if (mediaItem.size > 1024 * 1024 * 200) { //不支持大于200M的视频
            HDToastUtil.show(getString(R.string.trans_video_support_200M))
            return false
        }
        if (mediaItem.duration > 1000 * 60 * 60 * 3) { //不支持大于3小时的视频
            HDToastUtil.show(getString(R.string.trans_video_support_3H))
            return false
        }
        return true
    }
}